package com.future.controller;

import javax.validation.constraints.NotNull;

import com.future.common.annotation.ControllerMapping;
import com.future.common.base.BaseController;
import com.future.dao.NewsDao;
import com.future.model.News;
import com.future.requestbean.NewsAdd;
import com.future.requestbean.NewsUpdate;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.tx.Tx;

@ControllerMapping("/news")
public class NewsController extends BaseController {
	@Inject
	private NewsDao newsDao;

	public void queryNews() {
		renderResult("news", this.newsDao.findAll());
	}

	@Before(Tx.class)
	public void deleteNews(@NotNull(message = "请选择要删除的新闻") Long newsId) {
		this.newsDao.deleteById(newsId);
		renderSuccess();
	}

	@Before(Tx.class)
	public void addNews() {
		NewsAdd newsAdd = getJsonBody(NewsAdd.class);
		News news = beanToModel(newsAdd, News.class);
		String newsImg = getFirstImg(newsAdd.getContent());
		news.setNewsimg(newsImg);
		this.newsDao.save(news);
		renderSuccess();
	}

	@Before(Tx.class)
	public void newsUpdate() {
		NewsUpdate newsUpdate = getJsonBody(NewsUpdate.class);
		News news = beanToModel(newsUpdate, News.class);
		String newsImg = getFirstImg(newsUpdate.getContent());
		news.setNewsimg(newsImg);
		this.newsDao.update(news);
		renderSuccess();
	}
}
